package ExpressThree;

//双向循环链表
public class LinkList<T> {
    private LinkListNode<T> head;
    private int length=0;
    static class LinkListNode<T>{
        T data;
        LinkListNode<T> pre,next;
        LinkListNode(T data){
            this.data=data;
        }
    }
    public void add(T t){
        //容错
        if(t!=null) {
            if (head == null) {
                head = new LinkListNode<>(t);
                head.next = head;
                head.pre = head;

            } else {
                LinkListNode<T> temp = new LinkListNode<>(t);
/*
                temp.next = head.next;
                head.next.pre = temp;
                head.next = temp;
                temp.pre = head;

                head = head.next;//保持在尾部
            */
                head.pre.next=temp;
                temp.pre=head.pre;
                temp.next=head;
                head.pre=temp;
            }
            length++;
        }
    }
    //根据下标进行查找
    public T get(int index){
        if(index>=length||index<0) {
            return null;
        } else{
          LinkListNode<T> p=head;
          while(index--!=0){
              p=p.next;
          }
          return p.data;
        }
    }

    public T remove(){
        if(length>0) {
            LinkListNode<T> pt;

            pt=head.next;
            pt.next.pre=head;
            head.next=pt.next;
            //置空引用
            pt.next=pt.pre=null;

            length--;
            if(length==0)
                head=null;
            return pt.data;
        }
        return null;
    }
    public T remove(T data){
        //值相同就删除
        //容错
        if(data!=null) {
            int len = length;
            //根据次数判断
            while (len-- != 0) {
                if (head.data.equals(data))
                    break;
                head = head.next;
            }
            //如果找到了
            if (head.data == data) {
                head.pre.next = head.next;
                head.next.pre = head.pre;
                //获得该节点
                LinkListNode<T> temp = head;
                head = head.next;
                //该删除节点引用置空
                temp.pre = temp.next = null;
                length--;
                if (length == 0) {
                    head = null;
                }
                return temp.data;
            }
        }
        return null;
    }

    public int size() {
        //获取长度
        return length;
    }

}
